﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using ZerAx.Tweaks;

namespace BlockOS.Client
{
    public class EntityDataStorage
    {
        private readonly int maxEntityCount;
        public readonly Dictionary<int, EntityData> entities = new();
        public EntityData this[int entityId]
        {
            get => entities[entityId];
            set
            {
                if (entities.ContainsKey(entityId))
                {
                    entities[entityId] = value;
                }
                else
                {
                    AddEntity(entityId, value);
                }
            }
        }

        public (int, EntityData)[] Entities => entities.Select(x => (x.Key, x.Value)).ToArray();

        private Vector3 cachedDetectPosition;

        public EntityDataStorage(int maxEntityCount)
        {
            this.maxEntityCount = maxEntityCount;
        }

        public void SetDetectPosition(Vector3 detectPosition)
        {
            cachedDetectPosition = detectPosition;
        }

        private void AddEntity(int entityId, EntityData entity)
        {
            if (entities.Count > maxEntityCount)
            {
                RemoveTooFarEntities();
            }


            entities.Add(entityId, entity);
        }

        public void RemoveTooFarEntities()
        {
            var tobeRemoved = entities
                .OrderByDescending((pair) => MathUtil.ManhattanDistance(pair.Value.GetPosition().ToVec(), cachedDetectPosition))
                .Take(entities.Count - maxEntityCount);
            foreach (var entity in tobeRemoved)
            {
                entities.Remove(entity.Key);
            }
        }
    }
}
